<?php

namespace App\Http\Controllers\Api\V1;

use App\Models\Order;
use App\Models\Reward;
use App\Models\OrderItem;
use App\Models\SeckillProduct;
use App\Supports\Delivery\Express;
use App\Http\Controllers\Api\V1\Queries\OrderQuery;
use App\Services\MakeProductOrder\MakeProductOrder;
use App\Http\Controllers\Api\V1\Resources\OrderResource;
use App\Http\Controllers\Api\V1\Resources\OrderItemResource;
use App\Http\Controllers\Api\V1\Resources\RewardResource;
use App\Services\ReceiveProductOrder\ReceiveProductOrder;
use App\Services\MakeProductOrder\MakeProductOrderRequest;
use App\Services\ReceiveProductOrder\ReceiveProductOrderRequest;
use App\Services\CloseUnpaidProductOrder\CloseUnpaidProductOrder;
use App\Services\CloseUnpaidProductOrder\CloseUnpaidProductOrderRequest;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use App\Services\MakeSeckillOrder\ConfirmSeckillOrderRequest;
use App\Services\ApplySeckillProductBatchPay\ApplySeckillProductBatchPayRequest;
use App\Services\ApplySeckillProductBatchPay\ApplySeckillPorductBatchPay;
use App\Services\MakeSeckillOrder\CloseUnpaidSeckillOrder;
use Illuminate\Support\Facades\Cache;

class OrdersController extends Controller
{
	public function index()
	{
		$condition = request("condition");
		$user = request()->user();



		if(!$condition || $condition =='all'){

			$res = $user->rewards()->paginate();
		}else{
			$isOpen = $condition == "isopen" ? true : false;
			$res = $user->rewards()->where("is_open",$isOpen)->orderByDesc('id')->paginate();
		}
		

	
		return  RewardResource::collection($res);
	}

	public function show()
	{
		$user = request()->user();
		$cid = request('cid');
		return response()->json($user->myOrderCache($cid));
	}

	public function count(): JsonResponse
	{
		$user = request()->user();

		return response()->json($user->myOrdersCacheCount());
	}

	public function counts(): JsonResponse
	{
		$counts = request()->user()->myOrdersCacheCount();
		return response()->json(['counts' => $counts]);
	}



	public function store()
	{
		$lock = Cache::lock('buy_product', 15);
		try {
			//if (! $lock->get()) fail('高峰拥挤，请再试');

			$request = app(MakeProductOrderRequest::class);

			$uid = $request->user()->id;
			$produtId = $request->product_id;
			
			$user = $request->user();
			$user->addReward($uid,$produtId);

            return response()->json(['code' => 200]);

		} finally {
			$lock->release();
		}
	}


	public function batchConfirm()
	{
		$lock = Cache::lock('confirm_order', 15);

		try {

			//if (! $lock->get()) fail('高峰拥挤，请再试');

			$request = app(ConfirmSeckillOrderRequest::class);


			$uid = $request->user()->id;
			$cacheIds = request('cache_ids');
			$address  = $request->getAddress();

			SeckillProduct::addAddressToCache($uid, $cacheIds,$address);

            return response(null, 204);

		} finally {
			$lock->release();
		}
	}


	public function batchPayByBalance()
	{
		$lock = Cache::lock('batch_pay_orders', 15);

		try {
			//if (! $lock->get()) fail('高峰拥挤，请再试');

			$request = app(ApplySeckillProductBatchPayRequest::class);

			app(ApplySeckillPorductBatchPay::class, [
				'user' => $request->user(),
				'unpaidCacheIds' => request('cache_ids'),
			])->pay();

            return response(null, 204);

		} finally {
			$lock->release();
		}
	}


    public function express()
    {
    	$cacheId = request("cache_id");
    	if(!$cacheId){
    		fail("缺少必要字段");
    	}
    	$result = app(Express::class)->trackCache($cacheId);
    	return response()->json(['data' => $result]);
    }

     public function close()
    {

    	$request = app(CloseUnpaidProductOrderRequest::class);

    	$user = $request->user();

		app(CloseUnpaidSeckillOrder::class, [
            'uid' => $user->id,
            'unpaidCacheId' => $request->cache_id
        ])->close();
		 return response(null, 204);
    }

    public function receive(ReceiveProductOrderRequest $request, Order $order)
    {
	    $this->authorize('own', $order);
	    app(ReceiveProductOrder::class, ['order' => $order])->receive();
	    return response(null, 204);
    }

    public function destroy(Order $order)
    {
    	$this->authorize('own', $order);
    	$order->delete();
	    return response(null, 204);
    }

    public function item($id)
	{
		$orderItem = OrderItem::findOrFail($id);
		return new OrderItemResource($orderItem);
	}
}
